import path from 'node:path';

/**
 * Converts a string to kebab-case.
 * Handles CamelCase, PascalCase, snake_case, and strings with spaces.
 * Ensures result is lowercase.
 * Example: 'helloWorld' -> 'hello-world', 'UserProfile' -> 'user-profile', 'read_file' -> 'read-file'
 * @param str The input string.
 * @returns The kebab-cased string.
 */
export function toKebabCase(str: string): string {
  if (!str) {
    return '';
  }

  // Add a hyphen before uppercase letters (but not at the beginning)
  // Replace underscores and spaces with hyphens
  // Convert multiple hyphens to a single hyphen
  // Convert to lowercase
  return str
    .replace(/([A-Z])/g, (match, _, offset) => (offset > 0 ? '-' : '') + match.toLowerCase()) // Handle Camel/Pascal
    .replace(/[_\s]+/g, '-') // Handle snake_case and spaces
    .replace(/-{2,}/g, '-') // Handle multiple hyphens
    .toLowerCase(); // Ensure lowercase
}

/**
 * Generates the base channel part from a file path relative to a base directory.
 * Converts directory names and the filename (without extension) to kebab-case.
 * @param fullPath The full path to the module file.
 * @param basePath The base path to calculate the relative path from (e.g., src/main).
 * @returns The kebab-cased channel prefix (e.g., 'api/user/profile-settings').
 */
export function getChannelPrefixFromPath(fullPath: string, basePath: string): string {
  const relativePath = path.relative(basePath, fullPath);
  // Normalize path separators to '/' for consistency
  const normalizedPath = relativePath.replace(/\\/g, '/');
  const parsedPath = path.parse(normalizedPath);

  const dirParts = parsedPath.dir ? parsedPath.dir.split('/') : [];
  const filePart = parsedPath.name; // Filename without extension

  const kebabParts = [...dirParts, filePart]
    .filter((part) => part) // Remove empty parts (e.g., leading slash)
    .map(toKebabCase); // Convert each part to kebab-case

  return kebabParts.join('/');
}
